package com.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author xu.biao
 * @version v1.0
 * @Package com.security.config
 * @data 2021/9/8 23:15
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/")
        .permitAll()
        .antMatchers("/level1/**")
        .hasRole("vip1")
        .antMatchers("/level2/**")
        .hasRole("vip2")
        .antMatchers("/level3/**")
        .hasRole("vip3");
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("name").passwordParameter("pwd");
//    http.formLogin();
    http.logout().logoutSuccessUrl("/");
    http.rememberMe().rememberMeParameter("remember");
    http.csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .passwordEncoder(new BCryptPasswordEncoder())
        .withUser("root")
        .password(new BCryptPasswordEncoder().encode("root"))
        .roles("vip1", "vip2", "vip3")
        .and()
        .withUser("alice")
        .password(new BCryptPasswordEncoder().encode("123"))
        .roles("vip1")
        .and()
        .withUser("ben")
        .password(new BCryptPasswordEncoder().encode("123123"))
        .roles("vip2", "vip3");
    }
}
